package com.marvels.loanapply.customer.controller;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageInfo;
import com.marvels.common.dto.MarvelsResultDTO;
import com.marvels.common.exception.MarvelsBusinessException;
import com.marvels.common.exception.MarvelsErrorCode;
import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.loanapply.api.MclaLinkmanMobileApi;
import com.marvels.loanapply.customer.dto.LoanCustomerParamsDTO;
import com.marvels.loanapply.customer.dto.LoanCustomerResultDTO;
import com.marvels.loanapply.customer.dto.SmsTemplateNew;
import com.marvels.loanapply.customer.service.LoanCustomerService;
import com.marvels.loanapply.dao.CmFakeInfoDao;
import com.marvels.loanapply.dto.CmFakeInfoDTO;
import com.marvels.loanapply.dto.MclaLoanApplyLinkmanDTO;
import com.marvels.loanapply.dto.NotBorrowedDto;

import cn.hutool.core.util.StrUtil;
import net.sf.json.JSONObject;

/**
 * 贷款用户管理
 * @author 吴俊峰
 */
@RestController
@RequestMapping("loanApply/customer/service")
public class LoanCustomerController {

	@Autowired
	private LoanCustomerService loanCustomerService;
	
	@Autowired
	private CmFakeInfoDao cmFakeInfoDao;
	
	@Autowired
	private MclaLinkmanMobileApi mclaLinkmanMobileApi;
	
	@Value("${loanid.prefix}")
	private String loanidPrefix;
	/**
	 * 获取贷款用户列表数据
	 * @return
	 */
	@RequestMapping("/loanCustomerList")
	@ResponseBody
	public MarvelsResultDTO queryLoanCustomerList(@RequestBody LoanCustomerParamsDTO loanCustomerParamsDTO){
		try {
			List<LoanCustomerResultDTO> list = loanCustomerService.queryLoanCustomerList(loanCustomerParamsDTO);
			MarvelsLogUtil.getInstance().info("获取用户列表返回结果=======》》》" + list);
			return MarvelsResultDTO.getResult(MarvelsErrorCode.SUCCESS.getValue(),MarvelsErrorCode.SUCCESS.getDesc(), list);
		}catch(MarvelsBusinessException e){
			MarvelsLogUtil.getInstance().error("获取用户列表异常=======》》》", e);
			return MarvelsResultDTO.getResult(MarvelsErrorCode.FAIL.getValue(),MarvelsErrorCode.FAIL.getDesc(), e.getMessage());
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("获取用户列表异常=======》》》", e);
			return MarvelsResultDTO.getResult(MarvelsErrorCode.ERROR.getValue(),MarvelsErrorCode.ERROR.getDesc(), e.getMessage());
		}
	}
	
	@RequestMapping("downloadCustomerListExcel")
	public void downloadCustomerListExcel(LoanCustomerParamsDTO loanCustomerParamsDTO,HttpServletRequest request, HttpServletResponse response){
		//String custName,String custCardNo, String productName,Date startCreatedDate,Date endCreatedDate
		OutputStream os = null;
		HSSFWorkbook workbook = null;
		try {
			workbook = loanCustomerService.downloadCustomerListExcel(loanCustomerParamsDTO,request,response);
	        os = response.getOutputStream();// 取得输出流        
	        response.setHeader("Content-disposition", "attachment; filename="+ new String("用户列表.xls".getBytes("UTF-8"),"ISO8859-1"));  
	        response.setContentType("application/x-download");// 定义输出类型      
	        workbook.write(os);
		}catch(MarvelsBusinessException e){
			MarvelsLogUtil.getInstance().error("导出excel异常！", e);
		} catch (IOException e) {
			MarvelsLogUtil.getInstance().error("导出excel异常！", e);
		}finally{
			 if (os != null) {
                 try { 
                	 os.close(); 
                }  catch (IOException e) { 
	                 MarvelsLogUtil.getInstance().error("关闭流异常！",e);
                } 
             } 
		}
	}
	
	
	/**
	 * 获取短信模板
	 * @return
	 */
	@RequestMapping("/getSmsTemplateNew")
	@ResponseBody
	public MarvelsResultDTO getSmsTemplateNew(){
		try {
			SmsTemplateNew smsTemplateNew = loanCustomerService.getSmsTemplateNew();
			MarvelsLogUtil.getInstance().info("用户列表获取短信模板返回结果=======》》》" + smsTemplateNew);
			return MarvelsResultDTO.getResult(MarvelsErrorCode.SUCCESS.getValue(), MarvelsErrorCode.SUCCESS.getDesc(), smsTemplateNew);
		}catch(MarvelsBusinessException e){
			MarvelsLogUtil.getInstance().error("用户列表获取短信模板异常=======》》》", e);
			return MarvelsResultDTO.getResult(MarvelsErrorCode.FAIL.getValue(), MarvelsErrorCode.FAIL.getDesc(), e.getMessage());
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("用户列表获取短信模板异常=======》》》", e);
			return MarvelsResultDTO.getResult(MarvelsErrorCode.ERROR.getValue(), MarvelsErrorCode.ERROR.getDesc(), e.getMessage());
		}
	}
	
	/**
	 * 获取短信模板
	 * @return
	 */
	@RequestMapping("/getSmsTemplate")
	@ResponseBody
	public MarvelsResultDTO getSmsTemplate(@RequestBody long id){
		try {
			String content = loanCustomerService.getSmsTemplate(id);
			MarvelsLogUtil.getInstance().info("用户列表获取短信模板返回结果=======》》》" + content);
			return MarvelsResultDTO.getResult(MarvelsErrorCode.SUCCESS.getValue(), MarvelsErrorCode.SUCCESS.getDesc(), content);
		}catch(MarvelsBusinessException e){
			MarvelsLogUtil.getInstance().error("用户列表获取短信模板异常=======》》》", e);
			return MarvelsResultDTO.getResult(MarvelsErrorCode.FAIL.getValue(), MarvelsErrorCode.FAIL.getDesc(), e.getMessage());
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("用户列表获取短信模板异常=======》》》", e);
			return MarvelsResultDTO.getResult(MarvelsErrorCode.ERROR.getValue(), MarvelsErrorCode.ERROR.getDesc(), e.getMessage());
		}
	}
	
	/**
	 * 发送短信
	 * @return
	 */
	@RequestMapping("/sendMsg")
	@ResponseBody
	public MarvelsResultDTO sendMsg(@RequestBody LoanCustomerParamsDTO loanCustomerParamsDTO){
		try {
			Boolean result = loanCustomerService.sendMsg(loanCustomerParamsDTO);
			MarvelsLogUtil.getInstance().info("用户列表发送短信返回结果=======》》》" + result);
			if(result){
				return MarvelsResultDTO.getResult(MarvelsErrorCode.SUCCESS.getValue(), MarvelsErrorCode.SUCCESS.getDesc(), "发送成功");
			}else{
				return MarvelsResultDTO.getResult(MarvelsErrorCode.FAIL.getValue(), MarvelsErrorCode.FAIL.getDesc(), "发送失败");
			}
		}catch(MarvelsBusinessException e){
			MarvelsLogUtil.getInstance().error("用户列表发送短信异常=======》》》", e);
			return MarvelsResultDTO.getResult(MarvelsErrorCode.FAIL.getValue(), MarvelsErrorCode.FAIL.getDesc(), e.getMessage());
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("用户列表发送短信异常=======》》》", e);
			return MarvelsResultDTO.getResult(MarvelsErrorCode.ERROR.getValue(), MarvelsErrorCode.ERROR.getDesc(), e.getMessage());
		}
	}
	
	
	/**
	 * 获取贷款用户列表数据
	 * @return
	 */
	@RequestMapping("/getLoanCustomerInfo")
	@ResponseBody
	public MarvelsResultDTO getLoanCustomerInfo(@RequestBody LoanCustomerParamsDTO loanCustomerParamsDTO){
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			LoanCustomerResultDTO data = loanCustomerService.getLoanCustomerInfo(loanCustomerParamsDTO);
			String loanId =  data.getLoanId();
			List<MclaLoanApplyLinkmanDTO> reloanList = mclaLinkmanMobileApi.selectByLoanId(loanId);
			result.put("customerData", data);
			result.put("reloanList", reloanList);
			MarvelsLogUtil.getInstance().info("获取用户详情返回结果=======》》》" + JSONObject.fromObject(data));
			return MarvelsResultDTO.getResult(MarvelsErrorCode.SUCCESS.getValue(),MarvelsErrorCode.SUCCESS.getDesc(), result);
		}catch(MarvelsBusinessException e){
			MarvelsLogUtil.getInstance().error("获取用户详情异常=======》》》", e);
			return MarvelsResultDTO.getResult(MarvelsErrorCode.FAIL.getValue(),MarvelsErrorCode.FAIL.getDesc(), e.getMessage());
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("获取用户详情异常=======》》》", e);
			return MarvelsResultDTO.getResult(MarvelsErrorCode.ERROR.getValue(),MarvelsErrorCode.ERROR.getDesc(), e.getMessage());
		}
	}
	
	@RequestMapping("black/list")
	@ResponseBody
	public MarvelsResultDTO blackList(@RequestBody CmFakeInfoDTO cmFakeInfoDTO){
		MarvelsLogUtil.getInstance().info("入参customerName:"+cmFakeInfoDTO.getCustomerName()+",mobile:"+cmFakeInfoDTO.getMobile());
		PageInfo<CmFakeInfoDTO> pageInfo = null;
		try {
			pageInfo = loanCustomerService.getCmFakeInfoList(cmFakeInfoDTO.getPageNum(), cmFakeInfoDTO.getPageSize(), cmFakeInfoDTO.getCustomerName(), cmFakeInfoDTO.getMobile());
		} catch (MarvelsBusinessException e) {
			MarvelsLogUtil.getInstance().error("业务异常", e);
			return MarvelsResultDTO.getResult(MarvelsErrorCode.FAIL.getValue(),e.getMessage(), e.getMessage());
		}catch (Exception e) {
			MarvelsLogUtil.getInstance().error("系统异常", e);
			return MarvelsResultDTO.getResult(MarvelsErrorCode.ERROR.getValue(),MarvelsErrorCode.ERROR.getDesc(), e.getMessage());
		}
		return MarvelsResultDTO.getResult(MarvelsErrorCode.SUCCESS.getValue(), MarvelsErrorCode.SUCCESS.getDesc(), pageInfo);
	}
	
	@RequestMapping("set/black/status")
	@ResponseBody
	public MarvelsResultDTO setblackStatus(@RequestBody CmFakeInfoDTO dto){
		MarvelsLogUtil.getInstance().info("入参ic_number:"+dto.getIcNumber()+",status:"+dto.getStatus());
		String icNumber = dto.getIcNumber();
		String status = dto.getStatus();
		String mobile = dto.getMobile();
		if(StringUtils.isNotBlank(icNumber)){
			icNumber = icNumber.trim().replaceAll(" ", "");
		}
		if(StringUtils.isNotBlank(mobile)){
			mobile = mobile.trim().replaceAll(" ", "");
		}
		
		return MarvelsResultDTO.getResult(MarvelsErrorCode.ERROR.getValue(),MarvelsErrorCode.ERROR.getDesc(),"操作异常");
	}
	
	/**
	 * 手动添加黑名单
	 * @param dto
	 * @return
	 */
	@RequestMapping("addBlack")
	@ResponseBody
	public MarvelsResultDTO addBlack(@RequestBody CmFakeInfoDTO dto){
		if(StrUtil.isEmpty(dto.getMobile())){
			return MarvelsResultDTO.getResult(MarvelsErrorCode.ERROR.getValue(), "必要参数缺失", null);
		}
		dto.setStatus("0");
		CmFakeInfoDTO result = cmFakeInfoDao.selectCmFakeInfoInfo(dto);
		if (result == null || !StrUtil.equals(result.getStatus(), "0")) {
			return MarvelsResultDTO.getResult(MarvelsErrorCode.SUCCESS.getValue(),
					MarvelsErrorCode.SUCCESS.getDesc(), "操作成功");
		}else{
			return MarvelsResultDTO.getResult(MarvelsErrorCode.ERROR.getValue(), "该人已是黑名单，请勿重复添加", null);
		}
	}
	
	/**
	 * 获取未借款用户
	 * @return
	 */
	@RequestMapping("/selectNotBorrowedList")
	@ResponseBody
	public MarvelsResultDTO selectNotBorrowedList(@RequestBody LoanCustomerParamsDTO loanCustomerParamsDTO){
		try {
			MarvelsLogUtil.getInstance().info("获取用户列表返回结果=======》》》" );
			return MarvelsResultDTO.getResult(MarvelsErrorCode.SUCCESS.getValue(),MarvelsErrorCode.SUCCESS.getDesc(), loanCustomerService.selectNotBorrowedList(loanCustomerParamsDTO));
		}catch (Exception e) {
			MarvelsLogUtil.getInstance().error("获取用户列表异常=======》》》", e);
			return MarvelsResultDTO.getResult(MarvelsErrorCode.ERROR.getValue(),MarvelsErrorCode.ERROR.getDesc(), e.getMessage());
		}
	}
	
	/**
	 * 获取未借款用户
	 * @return
	 */
	@RequestMapping("/selectVerifyNotBorrowedList")
	@ResponseBody
	public MarvelsResultDTO selectVerifyNotBorrowedList(@RequestBody LoanCustomerParamsDTO loanCustomerParamsDTO){
		try {
			MarvelsLogUtil.getInstance().info("获取用户列表返回结果=======》》》" );
			return MarvelsResultDTO.getResult(MarvelsErrorCode.SUCCESS.getValue(),MarvelsErrorCode.SUCCESS.getDesc(),loanCustomerService.selectVerifyNotBorrowedList(loanCustomerParamsDTO));
		}catch (Exception e) {
			MarvelsLogUtil.getInstance().error("获取用户列表异常=======》》》", e);
			return MarvelsResultDTO.getResult(MarvelsErrorCode.ERROR.getValue(),MarvelsErrorCode.ERROR.getDesc(), e.getMessage());
		}
	}
	
	@RequestMapping("/downLoadNotBorrowedListExcel")
	public void downLoadNotBorrowedListExcel( LoanCustomerParamsDTO loanCustomerParamsDTO,HttpServletResponse response,HttpServletRequest request){
		BufferedOutputStream output = null;
		ByteArrayOutputStream byteArrayOutputStream=null;
		try {
			String fileName = "未借款用户列表.xls";
			List<NotBorrowedDto> dotList = null;
			if("0".equals(loanCustomerParamsDTO.getType()))
				dotList = loanCustomerService.selectNotBorrowedListWithoutPagesub(loanCustomerParamsDTO);
			else
				dotList = loanCustomerService.selectVerifyNotBorrowedListWithoutPagesub(loanCustomerParamsDTO);
			HSSFWorkbook wb = loanCustomerService.getNotBorrowedListExcel(dotList);
			byteArrayOutputStream = new ByteArrayOutputStream();
			wb.write(byteArrayOutputStream);
			byte[] bs = byteArrayOutputStream.toByteArray();
			byteArrayOutputStream.flush();
			byteArrayOutputStream.close();
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			
			output = new BufferedOutputStream(response.getOutputStream());
			// 中文文件名必须转码为 ISO8859-1,否则为乱码
			String fileNameDown = new String(fileName.getBytes(), "ISO8859-1");
			// 作为附件下载
			response.setHeader("Content-Disposition", "attachment;filename=" + fileNameDown);
			
			output.write(bs);
			response.flushBuffer();
			output.close();
			
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>下载未借款--查询列表异常:", e);
		}
		finally {
			if(byteArrayOutputStream!=null){
				try {
					byteArrayOutputStream.close();
				} catch (IOException e) {
					MarvelsLogUtil.getInstance().error(">>>>>>>>>关闭输出流异常byteArrayOutputStream", e);
				}
			}
			if (output != null)
				try {
					output.close();
				} catch (IOException e) {
					MarvelsLogUtil.getInstance().error(">>>>>>>>>关闭输出流异常output", e);
				}
		}
		
	}
	
	/**
	 * 发送短信
	 * @return
	 */
	@RequestMapping("/sendNotBorrowedMsg")
	@ResponseBody
	public MarvelsResultDTO sendNotBorrowedMsg(@RequestBody LoanCustomerParamsDTO loanCustomerParamsDTO){
		try {
			loanCustomerService.sendNotBorrowedMsg(loanCustomerParamsDTO.getMobileList());
			return MarvelsResultDTO.getResult(MarvelsErrorCode.SUCCESS.getValue(), MarvelsErrorCode.SUCCESS.getDesc(), null);
		}catch (Exception e) {
			MarvelsLogUtil.getInstance().error("未借款用户发送短信异常=======》》》", e);
			return MarvelsResultDTO.getResult(MarvelsErrorCode.ERROR.getValue(), MarvelsErrorCode.ERROR.getDesc(), e.getMessage());
		}
	}
	
	/**
	 * 允许重新进件
	 * @param loanCustomerParamsDTO
	 * @return
	 */
	@RequestMapping("/allowReEntry")
	@ResponseBody
	public MarvelsResultDTO allowReEntry(@RequestBody LoanCustomerParamsDTO loanCustomerParamsDTO){
		try {
			loanCustomerService.allowReEntry(loanCustomerParamsDTO);
			return MarvelsResultDTO.getResult(MarvelsErrorCode.SUCCESS.getValue(), MarvelsErrorCode.SUCCESS.getDesc(), null);
		}catch (Exception e) {
			MarvelsLogUtil.getInstance().error("允许重新进件异常=======》》》", e);
			return MarvelsResultDTO.getResult(MarvelsErrorCode.ERROR.getValue(), MarvelsErrorCode.ERROR.getDesc(), e.getMessage());
		}
	}
}
